package cn.findviewbydream.vant.plugin;

import com.intellij.openapi.project.Project;
import com.intellij.psi.impl.source.html.dtd.HtmlAttributeDescriptorImpl;
import com.intellij.psi.xml.XmlTag;
import com.intellij.xml.XmlAttributeDescriptor;
import com.intellij.xml.XmlAttributeDescriptorsProvider;
import org.jetbrains.annotations.Nullable;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * cn.findviewbydream.vant.plugin
 *
 * @author 白雨浓
 * date: 2019/11/11 15:48
 * content:
 */
public class VantAttributesProvider implements XmlAttributeDescriptorsProvider {

    private static Map<String, XmlAttributeDescriptor[]> cache = new ConcurrentHashMap<>();

    @Override
    public XmlAttributeDescriptor[] getAttributeDescriptors(XmlTag xmlTag) {

        if (!xmlTag.getName().startsWith("van-")) {
            return XmlAttributeDescriptor.EMPTY;
        }

        XmlAttributeDescriptor[] xs = cache.get(xmlTag.getName());
        if (xs != null) {
            return xs;
        }

        VantDoc.Item item = VantDoc.newInstance().getItem(xmlTag.getName());

        if (item == null) {
            return XmlAttributeDescriptor.EMPTY;
        }

        List<VantDoc.Prop> props = Optional.ofNullable(item.getProps()).orElse(Collections.emptyList());
        List<VantDoc.Method> methods = Optional.ofNullable(item.getMethods()).orElse(Collections.emptyList());

        List<VantAttributeDescriptor> list = new ArrayList<>(props.size() * 2 + methods.size() + 4);
        for (VantDoc.Prop prop : props) {
            list.add(new VantAttributeDescriptor(prop.getProp(), null));
            list.add(new VantAttributeDescriptor(":" + prop.getProp(), null));
        }
        list.add(new VantAttributeDescriptor(":key", null));

        for (VantDoc.Method method : methods) {
            if ("click".equals(method.getMethod())) {
                continue;
            }

            list.add(new VantAttributeDescriptor("@" + method.getMethod(), null));
        }

        list.add(new VantAttributeDescriptor("@click", null));
        list.add(new VantAttributeDescriptor("@click.native", null));
        list.add(new VantAttributeDescriptor("@click.stop", null));

        xs = list.toArray(new XmlAttributeDescriptor[0]);
        cache.put(xmlTag.getName(), xs);

        return xs;
    }

    @Nullable
    @Override
    public XmlAttributeDescriptor getAttributeDescriptor(String s, XmlTag xmlTag) {
        return null;
    }
}
